#include "timer_util.h"
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#define MAX_TIMERS 32

typedef struct {
    int in_use;
    int seconds;
    void (*callback)(void);
    pthread_t thread;
    int stop_flag;
} Timer;

static Timer timers[MAX_TIMERS];

static void* timer_thread_func(void* arg) {
    int timer_id = *(int*)arg;
    free(arg); // 不再使用
    Timer* t = &timers[timer_id];

    for (int i = 0; i < t->seconds; ++i) {
        if (t->stop_flag) return NULL;
        sleep(1);
    }

    if (!t->stop_flag && t->callback) {
        t->callback();
    }

    t->in_use = 0;
    return NULL;
}

int start_timer(int seconds, void (*callback)(void)) {
    for (int i = 0; i < MAX_TIMERS; ++i) {
        if (!timers[i].in_use) {
            timers[i].in_use = 1;
            timers[i].seconds = seconds;
            timers[i].callback = callback;
            timers[i].stop_flag = 0;

            int* arg = malloc(sizeof(int));
            *arg = i;

            if (pthread_create(&timers[i].thread, NULL, timer_thread_func, arg) != 0) {
                timers[i].in_use = 0;
                free(arg);
                return -1;
            }

            pthread_detach(timers[i].thread);
            return i;
        }
    }
    return -1; // 无可用定时器槽
}

void stop_timer(int timer_id) {
    if (timer_id >= 0 && timer_id < MAX_TIMERS && timers[timer_id].in_use) {
        timers[timer_id].stop_flag = 1;
        timers[timer_id].in_use = 0;
    }
}
